/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2013-2014 jfinal app. jfapp Group.
 */

package app.models.member;

import app.Const;
import app.kit.TypeKit;
import com.jfinal.plugin.activerecord.Model;
import goja.annotation.TableBind;
import goja.plugins.sqlinxml.SqlKit;
import goja.security.goja.SecurityKit;

import java.math.BigDecimal;

/**
 * <p>
 * The table rlm_account mapping model.
 * </p>
 */
@TableBind(tableName = "rlm_account",pkName= Const.FIELD_MEMBER)
public class Account extends Model<Account> {

    /**
     * The public dao.
     */
    public static final Account dao = new Account();

    private static final long serialVersionUID = 7991569483339545619L;

    public Account findbyMember(int memberId) {
        return findFirst(SqlKit.sql("member-account.findbyMember"), memberId);
    }

    public boolean checkTradePwd(String password) {
        return SecurityKit.checkPassword(getStr("trade_pwd_salt"),
                getStr("trade_pwd"),
                password);
    }


    public void subtract(BigDecimal amount){

        BigDecimal investments = TypeKit.getBigdecimal(this, "investments");
        if (BigDecimal.ZERO.compareTo(investments) < 0) {
            this.set("investments", investments.subtract(amount));
        }
        BigDecimal db_amount = TypeKit.getBigdecimal(this, Const.FIELD_AMOUNT);
        if (BigDecimal.ZERO.compareTo(db_amount) < 0) {
            this.set(Const.FIELD_AMOUNT, db_amount.subtract(amount));
        }
    }

    public void add(BigDecimal amount) {

        this.set("investments", TypeKit.getBigdecimal(this, "investments").add(amount));
        this.set("amount", TypeKit.getBigdecimal(this, Const.FIELD_AMOUNT).add(amount));
    }
}